import asyncio
import threading

import uvicorn
import aioredis
from aioredis import Redis
from fastapi import FastAPI

app = FastAPI()


REDIS_POOL = aioredis.ConnectionPool(host="127.0.0.1", port=6379, password="1", max_connections=100)


@app.get("/")
def index():
    return {"message": "hello world"}


@app.get("/red")
async def red(name):
    """异步操作接口"""
    print(f"{name} 请求来了")
    await asyncio.sleep(3)
    # 请求获取一个连接
    client = Redis(connection_pool=REDIS_POOL)
    try:
        print(f"{name} crud....")
        await client.set("life", 42)
        print(f"{name} The answer: {await client.get('life')}")
    finally:
        print(f"{name} connection disconnect....")
        await client.close()
        #await REDIS_POOL.disconnect()


if __name__ == "__main__":
    uvicorn.run("fastApi_test:app", host="127.0.0.1", port=5000, log_level="info", reload=True)